package com.storlead.sjwt.security;

import com.storlead.sjwt.model.JwtUser;
import com.storlead.sjwt.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @Author: Timo
 * @Date: 2019/3/21 11:45
 * @Description: 用户认证
 */
@Slf4j
@Component
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return new JwtUser(findUserByName(username));
    }

    private User findUserByName(String userName) {
        User user = new User();
        String password = new BCryptPasswordEncoder().encode("123");
        user.setPassword(password);
        user.setUserName(userName);
        if ("timo".equals(userName)) {
            user.setUserId(1);
            user.setRole("ROLE_ALL");

        } else if ("1".equals(userName)) {
            user.setUserId(1);
            user.setRole("ROLE_ADMIN");
        } else if ("2".equals(userName)) {
            user.setUserId(1);
            user.setRole("ROLE_TEST");
        }else {
            throw new UsernameNotFoundException("not find username ");
        }
        return user;
    }
}
